package com.capgemini.scaffold.config;

import com.capgemini.scaffold.common.BusinessException;
import com.capgemini.scaffold.common.ExceptionEnum;
import com.capgemini.scaffold.dto.LoginFromDTO;
import com.capgemini.scaffold.utils.ApplicationContextGetBeanHelper;
import com.capgemini.scaffold.utils.TokenCache;
import com.capgemini.scaffold.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.capgemini.scaffold.utils.CustomConstant.USER_LOGIN_TOKEN;

/**
 * @author ShuHao.Wen
 * @since 2022/10/20
 */
@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {


        // 获取请求头的token
        String token = request.getHeader(USER_LOGIN_TOKEN);
        // 判断为空||空字符串
        if (token == null || token.equals("")) throw new BusinessException(ExceptionEnum.TOKEN_IS_NULL);
        // 根据要注入的Bean的Class去获取Bean 上下文获取
        TokenCache cache = ApplicationContextGetBeanHelper.getBean(TokenCache.class);
        assert cache != null;
        Object loginFrom = cache.get(token);
        // 保存到线程域中
        UserHolder.saveUser((LoginFromDTO) loginFrom);
        return true;
    }

    // 在视图渲染完毕时回调
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 移除用户 避免内存泄露
        UserHolder.removeUser();
    }

}
